import requests

urlBefore = 'http://qzonestyle.gtimg.cn/qzone/em/e'
headers = {
"Host": "qzonestyle.gtimg.cn",
"Pragma": "no-cache",
"Cache-Control": "no-cache",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.113 Safari/537.36",
"Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
}

def getCodeEmoji(start, end):
    print('start', start, 'end:', end)
    for i in range(start, end):
        url = urlBefore + str(i) +  '@2x.gif'
        print(url, end='')
        retry = True
        while retry:
            try:
                r = requests.get(url=url, headers=headers)
                print('\t', r.status_code)
                if r.status_code == 200:
                    with open('img/e{}.gif'.format(i), 'wb') as f:
                        f.write(r.content)
                retry = False
            except Exception as e:
                print(e)
                retry = True


# 多进程查找
def multiProcess(start, end):
    splitNum = 32
    from multiprocessing import Process, Manager
    splitLen = (end-start) // splitNum
    processList = [None for n in range(splitNum)]
    # 分配
    for id in range(splitNum):
        if id != splitNum - 1 :
            processList[id] = Process(
                target=getCodeEmoji, 
                args=(start + id*splitLen, start + id*splitLen + splitLen)
            )
        else:
            processList[id] = Process(
                target=getCodeEmoji, 
                args=(start + id*splitLen, end)
            )
    for process in processList:
        process.start()

    def hasAlive(processList):
        result = False
        for process in processList:
            result = result or process.is_alive()
            if result == True:
                break
        return result

    while hasAlive(processList):
        # 等待进程结束
        pass

if __name__ == '__main__':
    multiProcess(0, 10000)
    multiProcess(10000, 10300)
    multiProcess(40000, 50000)
    multiProcess(100000, 130000)
    multiProcess(153000, 154000)
    multiProcess(164000, 166000)